<?php if (!defined('PmWiki')) exit();

/**	=== Attachtable utility functions ===
 *	Copyright 2007-2009 Eemeli Aro <eemeli@gmail.com>
 */

function AttachtableSortNameCmp( $a, $b ) {
	$ax = explode(',',$a);
	$bx = explode(',',$b);
	if ( ($ax[0]==$bx[0]) && (count($ax)>1) && (count($bx)>1) )
		return strcmp($bx[1],$ax[1]);
	else
		return strnatcasecmp($a,$b);
}

function AttachFilesizeString( $size, $markup=FALSE ) {
	global $AttachtablePrettyFilesize;
	$raw = number_format( $size );
	if ( !IsEnabled( $AttachtablePrettyFilesize, 1 ) ) return $raw;

	$units = array('','K','M','G','T','P');
	$c = 0;
	while ( $size >= 1000 ) { ++$c; $size /= 1024; } ## size ends up with at most 3 digits
	$str = number_format( $size, ( ($size<10) ? 1 : 0 ) ) . $units[$c];
	if ($markup) return "$str ($raw)";
	return "<span title='$raw'>$str</span>";
}

function AttachFiletype( $filename, $mime=TRUE, $charset=NULL ) {
	global $UploadExts;

	if (!$mime) return ( ini_get('safe_mode') || !function_exists('exec') ) ? '' : trim(@exec( 'file -b ' . escapeshellarg($filename) ));

	$ext = strtolower(pathinfo( $filename, PATHINFO_EXTENSION ));

	if ( function_exists('finfo_open') ) {
		$finfo = finfo_open(FILEINFO_MIME);
		$m = finfo_file($finfo, $filename);
		finfo_close($finfo);
	} else if ( function_exists('mime_content_type') ) {
		$m = mime_content_type($filename);
	} else $m = '';

	if ($m) {
		$split = strcspn($m,'; ');
		if ( !is_null($charset) && ( $split < strlen($m) ) ) $charset = trim( substr($m,$split), '; ' );
		$m = substr( $m, 0, $split );
	}

	switch($m) {
		case 'application/msword':
			if ( isset($UploadExts[$ext]) ) return $UploadExts[$ext];
			switch($ext) {
				case 'ppt': return 'application/vnd.ms-powerpoint';
				case 'xls': return 'application/vnd.ms-excel';
			}
			break;
		case '':
		case 'text/plain':
			if ( !ini_get('safe_mode') && function_exists('exec') ) {
				$m = trim(@exec( 'file -bi ' . escapeshellarg($filename) ));
				if ($m) {
					$split = strcspn($m,'; ');
					if ( !is_null($charset) && ( $split < strlen($m) ) ) $charset = trim( substr($m,$split), '; ' );
					$m = substr( $m, 0, $split );
				}
			}
			if (!$m) $m = @$UploadExts[$ext];
	}
	return $m;
}
